package com.zy.design.demo.behavioral;

/**
 * 解释器模式
 * 特点：为语言或表达式提供解释操作。(以类的形式解释)
 */
interface Expression {// 抽象表达式
    int interpret();// 解释方法，计算表达式的值
}
// 终结符表达式：常数
class Number implements Expression {
    private int number;

    public Number(int number) { this.number = number; }

    public int interpret() { return number; }// 返回常数的值
}
// 非终结符表达式：加法
class Add implements Expression {
    private Expression left, right;

    public Add(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }

    public int interpret() { return left.interpret() + right.interpret(); }// 加法操作
}
// 非终结符表达式：乘法
class Multiply implements Expression {
    private Expression left;
    private Expression right;

    public Multiply(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }
    public int interpret() {
        return left.interpret() * right.interpret();  // 乘法操作
    }
}
class Client2 {
    public static void main(String[] args) {
        // 3 + 5 * 2
        Expression expression = new Add(new Number(3), new Multiply(new Number(5), new Number(2)));

        // 计算结果
        int result = expression.interpret();
        System.out.println("Result: " + result);  // 输出：Result: 13
    }
}

